package org.jzoie.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.NumericField;

import org.jzoie.annotation.SearchProperty;
import org.jzoie.annotation.SearchProperty.Index;
import org.jzoie.annotation.SearchProperty.Store;
import org.jzoie.annotation.SearchProperty.Type;

public class TransferToDocument<T>
{
	private TextAnalyzeSpaceUtil analyzeSpaceUtil=new TextAnalyzeSpaceUtil();
	public Document toDocument(T t)
	{
		if (t== null) {
			return null;
		}
		Document document=new Document();
		Class cls=t.getClass();
		Field[] fields= cls.getDeclaredFields();
		Field field=null;
		String fieldName="";
		Method method=null;
		Object value=null;
		PropertyDescriptor descriptor=null;
		String fieldType="";
		for (int i = 0; i < fields.length; i++) 
		{
			
			try {
				field=fields[i];
				fieldName=field.getName();
				fieldType=field.getType().getSimpleName().toLowerCase();
				
				 descriptor= new PropertyDescriptor(fieldName, cls);
				 method = descriptor.getReadMethod();
				 value=method.invoke(t);
				 
				 SearchProperty searchProperty=method.getAnnotation(SearchProperty.class);
					
				 Store store=searchProperty.store();
				 Index index=searchProperty.index();
				 Type type=searchProperty.type();
				 
				org.apache.lucene.document.AbstractField documentField=null;
				org.apache.lucene.document.Field.Store fStore=null;
				if ("YES".equals(store.name()))
				{
					fStore=org.apache.lucene.document.Field.Store.YES;
				} else
				{
					fStore=org.apache.lucene.document.Field.Store.NO;
				}
				org.apache.lucene.document.Field.Index fIndex=null;
				if ("ANALYZED".equals(index.name()))
				{
					fIndex=org.apache.lucene.document.Field.Index.ANALYZED;
					value=analyzeSpaceUtil.spaceToOrderAppend(value+"");
					//value=analyzeSpaceUtil.innerText(value+"");
				} else
				{
					fIndex=org.apache.lucene.document.Field.Index.NOT_ANALYZED;
				}
				if ("NUMBER".equals(type.name()))
				{
					NumericField nField=new NumericField(fieldName,fStore,true);
					if (("int".equalsIgnoreCase(fieldType))||("integer".equalsIgnoreCase(fieldType)))
					{
						documentField=nField.setIntValue(Integer.parseInt(value+""));
					} else if ("double".equals(fieldType)) 
					{
						documentField=nField.setDoubleValue(Double.parseDouble(value+""));
					}else if ("long".equals(fieldType)) 
					{
						documentField=nField.setLongValue(Long.parseLong(value+""));
					} else if ("float".equals(fieldType)) 
					{
						documentField=nField.setFloatValue(Float.parseFloat(value+""));
					}
				} else
				{
					documentField=new org.apache.lucene.document.Field(fieldName, value+"", fStore,fIndex);
				}
				document.add(documentField);
				
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		return document;
	}
}
